package cn.ailearn.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@Slf4j
public class RedisConfiguration {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        log.info("开始创建Redis模板对象...");

        // 检查连接工厂是否为null
        if (redisConnectionFactory == null) {
            log.error("Redis连接工厂为空，无法创建RedisTemplate");
            throw new IllegalArgumentException("RedisConnectionFactory cannot be null");
        }

        try {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(redisConnectionFactory);

            // JSON序列化配置
            ObjectMapper objectMapper = new ObjectMapper();


            objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            // 使用安全的类型处理方式替代已废弃的enableDefaultTyping
            objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                    ObjectMapper.DefaultTyping.NON_FINAL);
            Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(objectMapper,Object.class);

            // String的序列化
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

            // key和hash的key都采用String的序列化方式
            template.setKeySerializer(stringRedisSerializer);
            template.setHashKeySerializer(stringRedisSerializer);

            // value和hash的value都采用jackson的序列化方式
            template.setValueSerializer(jsonRedisSerializer);
            template.setHashValueSerializer(jsonRedisSerializer);

            template.afterPropertiesSet();

            log.info("Redis模板对象创建成功");
            return template;
        } catch (Exception e) {
            log.error("创建Redis模板对象失败：{}", e.getMessage(), e);
            throw new RuntimeException("Failed to create RedisTemplate", e);
        }
    }
}